﻿using System.Collections.Generic;
using System.Linq;
using Accountant.DataModel;
using Accountant.Primitives;
using Accountant.Utils;
using Caliburn.Micro;

namespace Accountant.ViewModels
{
  public class AddExchangeViewModel : Screen
  {
    public override string DisplayName { get { return "Обмен валюты"; } set { } }

    public AccountantContext Context { get; set; }
    public List<Account> PossibleDebit { get; set; }
    public List<Account> PossibleCredit { get; set; }
    public IList<Currency> PossibleDebitCurrencies { get; set; }
    public IList<Currency> PossibleCreditCurrencies { get; set; }
    public Transaction FirstTransactionUnderCreation { get; private set; }
    public Transaction SecondTransactionUnderCreation { get; private set; }

    public AddExchangeViewModel(AccountantContext context)
    {
      Context = context;

      PossibleCredit = PossibleDebit = Context.Accounts
        .Where(a => !a.IsHidden && !a.IsAbstract)
        .AsEnumerable()
        .Where(a => a.IsAsset())
        .ToList();

      PossibleDebitCurrencies = PossibleCreditCurrencies = Context.Currencies;
      var exchangeAccount = Context.Accounts[(int)KnownAccounts.Exchange];
      FirstTransactionUnderCreation = new Transaction
                                   {
                                     Timestamp = Transaction.GenerateTimestamp(),
                                     Debit = PossibleDebit[0],
                                     Credit = exchangeAccount,
                                     Currency = PossibleCreditCurrencies.First(),
                                   };
      SecondTransactionUnderCreation = new Transaction
                                   {
                                     Debit = exchangeAccount,
                                     Credit = PossibleCredit[0],
                                     Currency = PossibleCreditCurrencies.Last(),
                                   };
    }
    public AddExchangeViewModel(AccountantContext context, ExchangeTransaction exchange)
    {
      Context = context;

      PossibleCredit = PossibleDebit = Context.Accounts
        .Where(a => !a.IsHidden && !a.IsAbstract)
        .AsEnumerable()
        .Where(a => a.IsAsset())
        .ToList();

      PossibleDebitCurrencies = PossibleCreditCurrencies = Context.Currencies;
      FirstTransactionUnderCreation = exchange.Transactions[0];
      SecondTransactionUnderCreation = exchange.Transactions[1];
    }

    public void Accept()
    {
      SecondTransactionUnderCreation.Timestamp = FirstTransactionUnderCreation.Timestamp;
      TryClose(true);
    }
    public void Cancel()
    {
      TryClose(false);
    }
  }
}